import axios from 'axios'
import { defineStore } from 'pinia'

export const useDockerImagesStore = defineStore('dockerImages', {
  state: () => ({
    images: [] as any[],
    loading: false,
    error: null as string | null
  }),
  actions: {
    setImages(list: any[]) {
      this.images = list || []
    },
    setLoading(loading: boolean) {
      this.loading = loading
    },
    setError(error: string | null) {
      this.error = error
    },
    async fetchImages() {
      this.setLoading(true)
      this.setError(null)
      try {
        const response = await axios.get('/api/docker/getDockerImages', {timeout: 5000});
        if (response.status == 200) {
          this.setImages(response.data)
          return true;
        } else {
            throw new Error(`Error fetching images: ${response.statusText}`)
        } 
      } catch (err: any) {
        this.setError(err.message || 'Failed to fetch Docker images')
        return false;
      } finally {
        this.setLoading(false)
      }
    },
    async removeImage(imageIdOrName: string) {
      // Placeholder for image removal logic
      const response = await axios.delete(`/api/docker/${imageIdOrName}`, {timeout: 5000});
      console.log('Remove image action triggered')
    },
    clear() {
      this.images = []
    }
  },
  getters: {
    isEmpty: (state) => state.images.length === 0,
  }
})
